﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AnalisisDeRiesgos.Dal;

namespace AnalisisDeRiesgos.Models.Management
{
    public class DetailsManagementModel
    {
        public int ManagementId { get; set; }
        public string Name { get; set; }
        public string Parent { get; set; }
        public string Responsible { get; set; }


        private riskanalysisEntities entities = new riskanalysisEntities();

        public DetailsManagementModel(int managementId)
        {
            var query = from m in entities.managements
                        where m.managementId == managementId && m.enabled
                        select new
                        {
                            ManagementId = m.managementId,
                            Name = m.name,
                            Responsible = (m.user.firstName + " " + m.user.lastName + " " + m.user.secondLastName),
                            Parent = m.management2.name
                        };

            var theManagement = query.FirstOrDefault();

            if (theManagement == null)
                throw new DetailsManagementException("La jefatura/gerencia especificada no existe");

            ManagementId = theManagement.ManagementId;
            Name = theManagement.Name;
            Responsible = theManagement.Responsible;
            Parent = theManagement.Parent;
        }

        public void DeleteManagement()
        {
            var managementList = from m in entities.managements
                                 where m.managementId == ManagementId && m.enabled
                                 select m;

            if (managementList.Count() <= 0)
                throw new DetailsManagementException("La Jefatura/Gerencia especificada no fue encontrada");

            if (managementList.First().managementId == 1)
                throw new DetailsManagementException("No puedes borrar la jefatura raiz");

            managementList.First().enabled = false;
            entities.SaveChanges();
        }
    }
}